package net.penguinmenac3.archivedb;

import java.util.LinkedList;

/**
 * @author Michael
 * This class provides the DB-functionality
 */
public class ArchiveDB {
	private SearchEngine se = new SearchEngine();
	/**
	 * Search for more related keywords, can be used for autofill and more.
	 * @param keywords
	 * @return
	 */
	public Key[] getMoreRelatedKeywords(String[] keywords, int filetype) {
		return se.getMoreKeywords(keywords, filetype);
	}
	/**
	 * Search entries in the DB.
	 * @param keywords
	 * @param filetype
	 * @return
	 */
	public Entry[] search(String[] keywords, int filetype, boolean fulltext, int crop) {
		Entry[] results = null;
		if (!fulltext) {
			results = se.search(keywords, filetype);
			results = sort(results, crop);
			for (int i = 0; i < results.length; i++) {
				results[i] = se.el.completeEntry(results[i]);
			}
		} else {
			results = se.searchFulltext(keywords, filetype);
			results = sort(results, crop);
		}
		return results;
	}
	private Entry[] sort(Entry[] results, int crop) {
		LinkedList<Entry> list = new LinkedList<Entry>();
		for (int i = 0; i < crop; i++) {
			Entry max = null;
			for (Entry e: results) {
				if ((max == null|| max.relevance < e.relevance)&&(!list.contains(e))) {
					max = e;
				}
			}
			if (max != null) {
				list.add(max);
			}
		}
		return list.toArray(new Entry[0]);
	}
	/**
	 * Add an Entry to the DB.
	 * @param entry
	 * @return
	 */
	public boolean push(Entry e) {
		boolean success = se.el.addEntry(e);
		se.update();
		return success;
	}
	/**
	 * Remove an Entry from the DB.
	 * @param ID
	 * @return
	 */
	public boolean delete(int ID) {
		boolean success = se.el.deleteEntry(ID);
		se.update();
		return success;
	}
	/**
	 * Remove an Entry from the DB.
	 * @param entry
	 * @return
	 */
	public boolean delete(Entry e) {
		return delete(e.ID);
	}
}
